<template>
    <div class="assessment-page">
        <!-- 导航栏 -->
        <van-nav-bar title="能力评估" left-text="返回" left-arrow @click-left="handleBack">
            <template #right>
                <span class="progress-text">{{ currentQuestion + 1 }}/{{ totalQuestions }}</span>
            </template>
        </van-nav-bar>

        <!-- 进度条 -->
        <div class="progress-section">
            <van-progress :percentage="progressPercentage" stroke-width="4" color="#1989fa" />
        </div>

        <!-- 评估内容 -->
        <div class="assessment-content">
            <!-- 开始页面 -->
            <div v-if="!assessmentStarted && !assessmentCompleted" class="start-section">
                <div class="intro-content">
                    <div class="intro-icon">
                        <van-icon name="chart-trending-o" size="64" color="#1989fa" />
                    </div>
                    <h2>社交能力评估</h2>
                    <p class="intro-text">
                        通过科学的评估问题，我们将帮助您了解自己在不同社交场景下的能力水平，
                        为您制定个性化的训练计划。
                    </p>
                    <div class="assessment-info">
                        <div class="info-item">
                            <van-icon name="clock-o" />
                            <span>预计用时：10-15分钟</span>
                        </div>
                        <div class="info-item">
                            <van-icon name="question-o" />
                            <span>题目数量：{{ totalQuestions }}题</span>
                        </div>
                        <div class="info-item">
                            <van-icon name="shield-o" />
                            <span>结果保密，仅用于个人提升</span>
                        </div>
                    </div>
                </div>
                <div class="start-actions">
                    <van-button type="primary" size="large" block @click="startAssessment">
                        开始评估
                    </van-button>
                </div>
            </div>

            <!-- 评估进行中 -->
            <div v-else-if="assessmentStarted && !assessmentCompleted" class="question-section">
                <QuestionCard v-if="currentQuestionData" :question="currentQuestionData"
                    :questionNumber="currentQuestion + 1" :totalQuestions="totalQuestions" @answer="handleAnswer" />
            </div>

            <!-- 评估完成 -->
            <div v-else-if="assessmentCompleted" class="completion-section">
                <div class="completion-content">
                    <div class="completion-icon">
                        <van-icon name="success" size="64" color="#07c160" />
                    </div>
                    <h2>评估完成！</h2>
                    <p class="completion-text">
                        恭喜您完成了社交能力评估！我们正在分析您的答案，
                        为您生成个性化的能力报告。
                    </p>
                    <div class="completion-stats">
                        <div class="stat-item">
                            <span class="stat-number">{{ totalQuestions }}</span>
                            <span class="stat-label">题目完成</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-number">{{ formatTime(assessmentDuration) }}</span>
                            <span class="stat-label">用时</span>
                        </div>
                    </div>
                </div>
                <div class="completion-actions">
                    <van-button type="primary" size="large" block @click="viewResults" :loading="submitting">
                        查看评估结果
                    </van-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { assessmentApi, type AssessmentQuestion, type AssessmentAnswer } from '@/api'
import { useUserStore } from '@/stores/user'
import QuestionCard from '@/components/QuestionCard.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const assessmentStarted = ref(false)
const assessmentCompleted = ref(false)
const submitting = ref(false)
const currentQuestion = ref(0)
const questions = ref<AssessmentQuestion[]>([])
const answers = ref<AssessmentAnswer[]>([])
const assessmentStartTime = ref<Date | null>(null)
const assessmentEndTime = ref<Date | null>(null)

// 计算属性
const totalQuestions = computed(() => questions.value.length)
const progressPercentage = computed(() => {
    if (totalQuestions.value === 0) return 0
    return Math.round((currentQuestion.value / totalQuestions.value) * 100)
})

const currentQuestionData = computed(() => {
    return questions.value[currentQuestion.value] || null
})

const assessmentDuration = computed(() => {
    if (!assessmentStartTime.value || !assessmentEndTime.value) return 0
    return Math.floor((assessmentEndTime.value.getTime() - assessmentStartTime.value.getTime()) / 1000)
})

// 方法
const loadQuestions = async () => {
    try {
        const response = await assessmentApi.getAssessmentQuestions()
        questions.value = response.data
    } catch (error) {
        console.error('加载评估题目失败:', error)
        showToast('加载题目失败，请重试')
    }
}

const startAssessment = () => {
    assessmentStarted.value = true
    assessmentStartTime.value = new Date()
    currentQuestion.value = 0
    answers.value = []
}

const handleAnswer = (answer: any) => {
    // 保存答案
    const assessmentAnswer: AssessmentAnswer = {
        question_id: currentQuestionData.value!.id,
        answer_value: answer.value,
        answer_text: answer.text || null,
        response_time: Date.now() - (assessmentStartTime.value?.getTime() || 0)
    }

    answers.value.push(assessmentAnswer)

    // 进入下一题或完成评估
    if (currentQuestion.value < totalQuestions.value - 1) {
        currentQuestion.value++
    } else {
        completeAssessment()
    }
}

const completeAssessment = () => {
    assessmentCompleted.value = true
    assessmentEndTime.value = new Date()
}

const viewResults = async () => {
    try {
        submitting.value = true

        // 提交评估结果
        const response = await assessmentApi.submitAssessment(userStore.userInfo!.id, {
            answers: answers.value,
            duration: assessmentDuration.value,
            completed_at: assessmentEndTime.value!.toISOString()
        })

        // 跳转到结果页面，使用用户ID作为参数
        router.push({
            name: 'AssessmentResult',
            params: { assessmentId: userStore.userInfo!.id.toString() }
        })
    } catch (error) {
        console.error('提交评估失败:', error)
        showToast('提交失败，请重试')
    } finally {
        submitting.value = false
    }
}

const handleBack = async () => {
    if (assessmentStarted.value && !assessmentCompleted.value) {
        try {
            await showConfirmDialog({
                title: '确认退出',
                message: '评估尚未完成，退出后进度将丢失，确认退出吗？'
            })
            router.back()
        } catch {
            // 用户取消
        }
    } else {
        router.back()
    }
}

const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds}秒`
}

// 生命周期
onMounted(() => {
    loadQuestions()
})

// 防止用户意外离开页面
onUnmounted(() => {
    // 清理工作
})
</script>

<style lang="scss" scoped>
.assessment-page {
    min-height: 100vh;
    background: #f7f8fa;

    .progress-section {
        padding: 16px 20px;
        background: white;
        border-bottom: 1px solid #ebedf0;

        .progress-text {
            font-size: 14px;
            color: #646566;
        }
    }

    .assessment-content {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .start-section {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 40px 20px 20px;

        .intro-content {
            flex: 1;
            text-align: center;

            .intro-icon {
                margin-bottom: 24px;
            }

            h2 {
                font-size: 24px;
                color: #323233;
                margin: 0 0 16px 0;
                font-weight: 600;
            }

            .intro-text {
                font-size: 16px;
                color: #646566;
                line-height: 1.6;
                margin: 0 0 32px 0;
            }

            .assessment-info {
                .info-item {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                    padding: 12px 0;
                    font-size: 14px;
                    color: #646566;

                    .van-icon {
                        color: #1989fa;
                    }
                }
            }
        }

        .start-actions {
            padding-top: 20px;
        }
    }

    .question-section {
        flex: 1;
        padding: 20px;
    }

    .completion-section {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 40px 20px 20px;

        .completion-content {
            flex: 1;
            text-align: center;

            .completion-icon {
                margin-bottom: 24px;
            }

            h2 {
                font-size: 24px;
                color: #323233;
                margin: 0 0 16px 0;
                font-weight: 600;
            }

            .completion-text {
                font-size: 16px;
                color: #646566;
                line-height: 1.6;
                margin: 0 0 32px 0;
            }

            .completion-stats {
                display: flex;
                justify-content: center;
                gap: 40px;

                .stat-item {
                    text-align: center;

                    .stat-number {
                        display: block;
                        font-size: 24px;
                        color: #1989fa;
                        font-weight: bold;
                        margin-bottom: 4px;
                    }

                    .stat-label {
                        font-size: 14px;
                        color: #646566;
                    }
                }
            }
        }

        .completion-actions {
            padding-top: 20px;
        }
    }
}
</style>